from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse,JsonResponse
from django.views import View

from main.models import Article
from operate.form import CommentForm
from operate.models import Collect,Comment
from user.models import CustomUser
from django.urls import reverse_lazy


# Create your views here.

def collect(request):
    a_id = request.POST.get("article")
    u_id = request.POST.get("user")
    user = get_object_or_404(CustomUser,id=u_id)
    article = get_object_or_404(Article,id=a_id)

    collect = Collect.objects.filter(user=user,article=article).first()
    if collect is None:
        r = Collect.objects.create(user=user,article=article)
        return JsonResponse({'code': 0, 'status': 'success', 'msg': '收藏成功'})
    else:
        collect.delete()
        return JsonResponse({'code': 0, 'status': 'success', 'msg': '取消收藏成功'})



def add_comment(request):
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            user = CustomUser.objects.get(id=request.POST.get("user"))
            article = Article.objects.get(id=request.POST.get("article"))
            instance = Comment.objects.create(user=user,article=article,content=form.cleaned_data["content"])
            return JsonResponse({'code':0,'msg':"评论成功",'data':{
                "id":instance.id,
                "content":instance.content,
                "username":user.username,
                "head":user.head.url,

            }})
    return JsonResponse({'status': 'error', 'msg': '仅支持 POST 请求'})